# -*- coding:utf-8 -*-
# @Time    :2022/1/14 0014 19:52
# AUTHOR   :JUNWEI
# @Email   :2328014713@qq.com
# @File    :serializers.py
# @Software:PyCharm

from rest_framework import serializers
from .models import Student, Department

"""
序列化器
本质上就是一个类 和模型类类似
用于json与模型对象互转，以及校验数据
定义的属性就是需要参与转换的字段
instance 序列化 传入模型
data 反序列化
"""

# class StudentSerializers(serializers.Serializer):
#     SEX_CHOICES = (
#         (0, '女'),
#         (1, '男')
#     )
#     id = serializers.IntegerField(label='ID', read_only=True) #只读
#     name = serializers.CharField(max_length=30, label='姓名')
#     age = serializers.IntegerField(label='年龄', required=False) # required=False可以不传
#     sex = serializers.IntegerField(label='性别', null=True, blank=True, choices=SEX_CHOICES)
#     create_time = serializers.DateTimeField(auto_now_add=True, label='创建时间')
#     update_time = serializers.DateTimeField(auto_now=True, label='更新时间')
#     is_delete = serializers.BooleanField(default=False, label='逻辑删除')

class StudentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Student # 指定序列化映射的模型类
        fields = '__all__' # 指定映射字段 __all__全部字段
        # fields = ['id','name', 'age'] # 指定映射具体字段
        # exclude = ['id'] #映射除ID以外所有的字段
        # 修改映射字段
        extra_kwargs = {
            'age': {'min_value': 0,'max_value': 120},
            # 'sex': {'required': True}
        }
        read_only_fields = ['id']  # 只读

    # 增加额外的字段校验(单个字段）
    # def validated_name(self, value):
    #     if 'moran' not in value.lower():
    #         raise serializers.ValidationError('name error')
    #     return value

    # 对象级别的校验
    # def validated(self, data):
    #     if 'moran' not in data['name'].lower():
    #         raise serializers.ValidationError('name error')
    #     return data


class DepartmentSerializer(serializers.ModelSerializer):
    student_set = StudentSerializers(many=True, required=False)
    class Meta:
        model = Department
        fields = "__all__"